home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Magnum One
/
Magnum One (Mid-American Digital) (Disc Manufacturing).iso
/
d12
/
cgazv5n4.arc
/
STRINGC.CPP
< prev
next >
Wrap
C/C++ Source or Header
|
1991-09-23
|
2KB
|
84 lines
//--- STRINGC.CPP ------------------------ Listing 2 -----------
// Implementation of string class
// by Bruce Eckel. See Listing 1 for copyright information.
//--------------------------------------------------------------
#include "stringc.h"
void string::erase_string() {
cursor = head;
while(cursor) {
cursor = cursor->next;
delete head;
head = cursor;
}
}
void string::defragment() {
if(head->next == NULL) return; // only 1 piece
cursor = head;
char* temp = new char[Length + 1];
int index = 0;
while(cursor != NULL) {
strcpy(temp + index, cursor->str);
index += cursor->plength;
cursor = cursor->next;
}
erase_string();
cursor = head = new piece(NULL,temp); // Length stays the same
}
string::string(char * s) {
cursor = head = new piece(NULL, s);
Length = strlen(s);
}
void string::append(char * s) {
cursor->next = new piece(NULL, s);
cursor = cursor->next;
Length += cursor->plength;
}
void string::prepend(char* s) {
head = new piece(head,s);
Length += head->plength;
}
void string::insert(int position, char* s) {
if(position <= 0) { prepend(s); return; }
if(position >= Length) { append(s); return; }
defragment();
head->break_piece(position);
cursor = head->next;
head->next = new piece(head->next, s); // insert the piece
Length += head->next->plength; // ... and adjust the length
}
void string::erase(int position, int count) {
defragment();
if(position < 0 || position >= Length) return;
head->break_piece(position);
cursor = head->next;
if(count > cursor->plength) count = cursor->plength;
cursor->break_piece(count); // break off the end to save
Length -= head->next->plength // adjust length
head->next = cursor->next; // thread past the piece to delete
delete cursor;
cursor = head->next; // put the cursor at the end
}
int string::search(char * findstring) {
defragment();
char * start = strstr(head->str, findstring);
if(start == NULL) return -1; // means string not found
return start - head->str; // index of starting position
}
void string::print() {
piece * cur = head;
while(cur) {
cur->print(); // calls piece::print() since cur is a piece
cur = cur->next;
}
printf("\n");
}